<?php
/**
 * CK 开发框架
 * User: Clake
 * Date: 15/6/11
 * Time: 23:27
 */

namespace CK\Core;

/**
 * Class Module
 * 核心模块类
 * @package CK\Core
 */
class Module extends Base{
    /**
     * 模块配置项
     * @var array
     */
    protected $_conf=[];
    /**
     * 当前模块加载的控制器
     * @var Controller
     */
    protected $_controller;

    /**
     * 当前要执行的控制器动作
     * @var
     */
    protected $_action;

    /**
     * 当前模块实例化类
     * @var
     */
    private static $_instance;

    /**
     * 初始化当前模块
     * @return Module
     */
    public static function inst() {
        if (!isset(self::$_instance)) {
            $class = get_called_class();
            self::$_instance = new $class();
        }
        return self::$_instance;
    }

    public function __construct() {
        //加载当前模块配置
        $this->loadConfig();
    }

    /**
     * 加载配置
     */
    private function loadConfig() {
        $class = get_called_class();
        $class = substr($class,0,strrpos($class,'\\'));
        $conf = Config::inst('main')->get('module.'.$class);
        if (is_array($conf)) {
            $this->_conf = array_merge($this->_conf,$conf);
        }
    }

    /**
     * 设置要执行的路由动作
     * @param $action
     */
    public function setAction($action) {
        $this->_action = $action;
    }

    /**
     * 设置路由的控制器
     * @param $controller
     */
    public function setController($controller) {
        $this->_controller = $controller;
    }

    public function loadView($def_tpl) {
        if (isset($this->_controller)) {
            $this->_controller->setDefaultTemplate($def_tpl);
            $this->_controller->setView(View::inst());
        }
    }

    /**
     * 开始运行模块
     */
    public function run() {
        //得到控制器类
        $this->setController(Router::inst()->getController());
        //设置当前控制器默认模板
        $def_tpl = Router::inst()->getRouterParam('module').'.'
            .hump2under(Router::inst()->getRouterParam('controller'))
            .'.'.hump2under(Router::inst()->getRouterParam('action'));
        //加载VIEW显示器
        $this->loadView($def_tpl);
        //得到执行动作
        $this->setAction(Router::inst()->getAction());
        call_user_func([$this->_controller,$this->_action]);
    }
}